package com.example.test04

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class ModifyInfoActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_modify_info)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        findViewById<Button>(R.id.save).setOnClickListener({
            val intent = Intent()
            val name = findViewById<EditText>(R.id.name).text.toString().takeIf { it.isNotEmpty() }
            val sex_id = findViewById<RadioGroup>(R.id.sex).checkedRadioButtonId
            val sex = when (sex_id) {
                R.id.male -> true
                R.id.female -> false
                -1 -> null
                else -> null
            }
            val stuno = findViewById<EditText>(R.id.stuno).text.toString().takeIf { it.isNotEmpty() }
            val pno = findViewById<EditText>(R.id.pno).text.toString().takeIf { it.isNotEmpty() }
            val mail = findViewById<EditText>(R.id.mail).text.toString().takeIf { it.isNotEmpty() }
            val hobbyList = mutableListOf<String>()
            if (findViewById<CheckBox>(R.id.hobby_eat).isChecked) {
                hobbyList.add(findViewById<CheckBox>(R.id.hobby_eat)?.text.toString())
            }
            if (findViewById<CheckBox>(R.id.hobby_sleep).isChecked) {
                hobbyList.add(findViewById<CheckBox>(R.id.hobby_sleep)?.text.toString())
            }
            if (findViewById<CheckBox>(R.id.hobby_chat).isChecked) {
                hobbyList.add(findViewById<CheckBox>(R.id.hobby_chat)?.text.toString())
            }
            if (findViewById<CheckBox>(R.id.hobby_study).isChecked) {
                hobbyList.add(findViewById<CheckBox>(R.id.hobby_study)?.text.toString())
            }
            val hobby = if (hobbyList.isEmpty()) null else hobbyList.joinToString("、")
            intent.putExtra("user_info", UserInfo(name, sex, stuno, pno, mail, hobby))
            setResult(RESULT_OK, intent)
            finish()
        })
    }
}